package com.ysw.drivers.service.impl;

import com.ysw.drivers.config.DBContextHolder;
import com.ysw.drivers.config.DynamicDataSource;
import com.ysw.drivers.mapper.DataSourceMapper;
import com.ysw.drivers.pojo.DataSource;
import com.ysw.drivers.service.DBChangeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DBChangeServiceImpl implements DBChangeService {

    private static final Logger LOG = LoggerFactory.getLogger(DBChangeServiceImpl.class);


    @Autowired
    private DataSourceMapper dataSourceMapper;

    @Autowired
    private DynamicDataSource dynamicDataSource;


    @Override
    public List<DataSource> get() {
        return dataSourceMapper.get();
    }

    @Override
    public boolean changeDb(String dataSourceId) throws Exception {
        //默认切换到主数据源,进行整体资源的查找
        DBContextHolder.clearDataSource();
        List<DataSource> dataSourceList = dataSourceMapper.get();

        for (DataSource dataSource : dataSourceList) {
            if (dataSource.getDatasourceId().equals(dataSourceId)) {
                LOG.info("需要使用的的数据源已经找到,dataSourceId是：{}", dataSource.getDatasourceId());
                //创建数据源连接&检查 若存在则不需重新创建
                dynamicDataSource.createDataSourceWithCheck(dataSource);
                //切换到该数据源
                DBContextHolder.setDataSource(dataSource.getDatasourceId());
                return true;
            }
        }
        return false;
    }
}
